<template>
	<view class="contont">
		<nav-bar :title="pageInfo.navbarTitle" :iconLeft="true" />
		<uni-forms :model="form" :rules="rules" ref="refForm" label-width="100px">
			<view class="content-bgc">
				<view class="b-con">
					<uni-forms-item label="入库单号" name="code">
						<uni-easyinput v-model="form.code" placeholder="请输入入库单号" class="iptBor" :inputBorder="false"
							:disabled="switchCode" />
					</uni-forms-item>
					<view class="hint-text">只有“已审核”状态的委外加工单，才会出现在下拉框中</view>
					<uni-forms-item label="委外加工单号" name="machining" required>
						<uni-data-select mode="underline" placeholder="请选择委外加工单号" v-model="form.machining"
							:localdata="machining_list" :clear="false" :disabled="pageInfo.type == 'edit'" @change="order_change" />
					</uni-forms-item>
					<uni-forms-item label="入库日期" name="in_date" required>
						<view class="dateTimeBottom">
							<uni-datetime-picker type="datetime" placeholder="请选择入库日期" :clear-icon="false" v-model="form.in_date"
								:border="false" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="备注：" name="desc">
						<uni-easyinput type="textarea" v-model="form.desc" placeholder="请输入备注" />
					</uni-forms-item>
				</view>
				<view class="b-con">
					<u-cell-group :border="false">
						<u-cell :isLink="true" :border="false" :title="`产品数量（${form.product_list.length}）`"
							@click="car_popupShow = true">
							<view slot="value" class="cell-text">点击查看 </view>
						</u-cell>
					</u-cell-group>
				</view>
			</view>
			<custom-popup :popupShow="car_popupShow" mode="bottom" :title="'生产领料'" class="car-popup-custom"
				@close="car_popupShow = false" height="70vh">
				<z-paging v-if="car_popupShow" ref="paging_car" :refresher-enabled="false" :loading-more-enabled="false" :fixed="false"
					v-model="form.product_list" @query="queryList_car">
					<template #top>
						<view class="zpagin_top">
							<view class="search">
								<view class="hint-text">本期入库数量应在 0 和 (加工产品数量 - 已入库数量) 之间</view>
							</view>
						</view>
					</template>
					<template #bottom>
						<view>
							<view style="padding: 40rpx 20rpx; background-color: transparent;">
								<u-button type="primary" text="提交" @click="save"></u-button>
							</view>
						</view>
					</template>
					<uni-card class="section_item" v-for="(item, index) in form.product_list" :key="index" :title="item.name"
						:sub-title="item.code" margin="5px" spacing="0">
						<view class="ctent">规格：{{ item.specification }}</view>
						<view class="con">
							<view class="ctent ">基本单位：{{ item.unit_main }}</view>
							<view class="ctent ">加工产品数量：{{ item.num }}</view>
						</view>
						<view class="con">
							<view class="ctent ">加工单价(元)：{{ item.machining_price }}</view>
							<view class="ctent ">已入库数量：{{ item.up_num }}</view>
						</view>
						<uni-forms-item label="入库仓库：" :name="`product_list[${index}].warehouse`" required
							:rules="[{ required: true, type:'number', errorMessage: `请选择【${index.name}】的入库仓库` }]">
							<uni-data-select placement="bottom" mode="underline" placeholder="请选择入库仓库" v-model="item.warehouse"
								:localdata="warehouse_list" :clear="false" />
						</uni-forms-item>
						<view class="con">
							<view class="ctent" style="flex: none;">本期入库数量：</view>
							<custom-num-box v-model="item.now_num" :min="0" @change="changeNum($event, item)"
								:asyncChange="true"></custom-num-box>
						</view>
					</uni-card>
				</z-paging>
			</custom-popup>
		</uni-forms>
	</view>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import enInApi from '../../../api/entrust/en_in'
import { generateCode, debounce } from '@/utils/index.js';
//页面标题
const pageInfo = reactive({
	navbarTitle: '委外加工入库',
	type: '',
	edit_id: null,
});

onLoad(option => {
	get_machining_list()
	get_warehouse_list()
	pageInfo.type = option.type
	if (option.type == 'edit') {
		pageInfo.navbarTitle = `${pageInfo.navbarTitle}(修改)`
		get_detail(option.id)
		pageInfo.edit_id = option.id
	} else {
		pageInfo.navbarTitle = `${pageInfo.navbarTitle}(新增)`
		form.code = generateCode('EI')
	}
})

//自动生成按钮
const switchCode = ref(true);
function switchChange(v) {
	if (v) {
		form.code = generateCode('EI')
	}
}

const refForm = ref(null)
const form = reactive({
	code: '',
	machining: null,
	in_date: null,
	desc: '',
	product_list: []
})
const fields = Object.keys(form);
const rules = {
	code: { rules: [{ required: true, errorMessage: '请输入入库单号' }] },
	machining: { rules: [{ required: true, type: 'number', errorMessage: '请选择委外加工单' }] },
	in_date: { rules: [{ required: true, errorMessage: '请选择入库日期' }] },
}
function get_detail(id) {
	machining_in_detail(id).then(res => {
		const record = uni.$lodash.pick(res, fields)
		Object.assign(form, record)
		enInApi.get_machining_in_product({ machining_product__machining__id: res.machining }).then(res2 => {
			form.product_list = res2.results.map(v => {
				return {
					id: v.machining_product.product.id,
					machining_product_id: v.machining_product.id,
					code: v.machining_product.product.code,
					name: v.machining_product.product.name,
					specification: v.machining_product.product.specification,
					unit_main: v.machining_product.product.unit_main,
					num: v.num,
					machining_price: v.price,
					up_num: v.up_num,
					now_num: v.now_num,
					warehouse: v.warehouse
				}
			})
		})
	})
}

function order_change(v) {
	form.product_list = []
	enInApi.get_machining_product({ machining__id: v }).then(res => {
		form.product_list = res.results.map(v => {
			return {
				id: v.product.id,
				machining_product_id: v.id,
				code: v.product.code,
				name: v.product.name,
				specification: v.product.specification,
				unit_main: v.product.unit_main,
				num: v.num,
				machining_price: v.machining_price,
				warehouse: null,
				up_num: v.up_num,
				now_num: 0
			}
		})
	})
}

function changeNum(e, row) {
	if (!row.warehouse) {
		return uni.$u.toast('请选择仓库')
	}
	if (e.value > row.num - row.up_num) {
		row.now_num = row.num - row.up_num
		return uni.$u.toast('本期入库数量不能超过(加工产品数量 - 已入库数量)')
	}
	row.now_num = e.value
}

const car_popupShow = ref(false)
const paging_car = ref(null)
function queryList_car() {
	paging_car.value.complete(form.product_list);
}

//提交操作
function save() {
	refForm.value.validate().then(() => {
		const params = uni.$lodash.cloneDeep(form) // 深拷贝一份form表单
		if (pageInfo.type == 'add') {
			enInApi.post_machining_in(params).then(res => {
				uni.$u.toast('添加成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		} else {
			//修改
			enInApi.patch_machining_in(params, pageInfo.edit_id).then((res) => {
				uni.$u.toast('修改成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		}

	}).catch((error) => {
		uni.$u.toast(error[0].errorMessage);
	})
}

const warehouse_list = ref([])
function get_warehouse_list() {
	const params = { page: 1, page_size: 99999 };
	enInApi.get_warehouse(params).then(res => {
		warehouse_list.value = res.results.map(v => ({
			text: v.name,
			value: v.id
		}))
	})
}

const machining_list = ref([])
function get_machining_list() {
	const params = { page: 1, page_size: 99999, status: 2 };
	enInApi.get_machining(params).then(res => {
		machining_list.value = res.results.map(v => ({
			text: v.code,
			value: v.id
		}))
	})
}
//返回上一级并刷新上一级页面
function backRefsh() {
	uni.navigateBack({
		delta: 1, // 返回的页面层数，1 表示返回上一级
		success: () => {
			uni.$bus.useBusEmit('en_in:refresh')
		}
	})
}
</script>

<style lang="scss" scoped></style>